package com.shop.model.controller;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shop.model.entity.UserTb;
import com.shop.model.mapper.UserTbMapper;
import com.shop.model.service.IUserTbService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;


/**
 * <p>
 *  前端控制器
 *  登录和登录页面的controller
 * </p>
 *
 * @author shop
 * @since 2018-12-03
 */
@Controller
public class UserTbController {
    @Autowired
    private IUserTbService iUserTbService;
    private UserTbMapper userTbMapper;
//     //登录
//    @RequestMapping("/login")
//    public String login(String username, String password,HttpServletRequest request) {
//        HttpSession session = request.getSession();
//        String userName=null;
//        String userImg=null;
//        if (null != username & null != password) {
//                QueryWrapper<UserTb> wrapper = new QueryWrapper<>();
//                wrapper.eq("user_name", username).eq("password", password);
//                UserTb userTb1 = iUserTbService.getOne(wrapper);
//                //我们从前端传回一个的两个值
//                System.out.println(userTb1);
//                //获取登陆者的头像和用户名
//                if (userTb1!=null){
//                    userName = userTb1.getNickname();
//                    userImg = userTb1.getUserImgUrl();
//                    Integer userId = userTb1.getUserId();
//                    //判断对象是否为空，不为空进入主页，返回登录页面
//                    session.setAttribute("userName",userName);
//                    session.setAttribute("userId",userId);
//                    session.setAttribute("userImg",userImg);
//                    //登录成功
//                    return "index";
//                }
//                //登录失败
//                request.setAttribute("failed","登录失败！请输入正确的登录名和密码！");
//                return "login";
//            }
//        return "login";
//    }


    //注册
    @RequestMapping("/register")
   public String register(UserTb userTb,HttpServletRequest request){

        System.out.println("注册用户信息"+userTb);
        //当你创建对象时对象的值为空，但是对象不为空
        //判断对象里面的值是否为空
        if(userTb.getPassword()!=null&userTb.getUserName()!=null&userTb.getNickname()!=null&userTb.getUserEmail()!=null){
            QueryWrapper<UserTb> wrapper = new QueryWrapper<>();
            wrapper.eq("user_name", userTb.getUserName());
            UserTb one = iUserTbService.getOne(wrapper);
            if(null!=one ){
                System.out.println("注册失败");
                request.setAttribute("failed","该账号已经存在！");
                    return "register";
            }else{
                userTb.setUserStatus(1);
                boolean save =iUserTbService.save(userTb);
                if (save){
                    System.out.println("注册成功");
                    return "login";
                }
                System.out.println("注册失败");
                return "register";
            }
        }
        return "register";
    }

    @RequestMapping("/login")
    //shiro认证登录
    public String login1(String username, String password,HttpServletRequest request,@RequestParam(defaultValue = "false",required = false) Boolean isok) {
        HttpSession session=request.getSession();
        System.out.println(username+"-----"+password);
        if (null != username & null != password) {
            QueryWrapper<UserTb> wrapper = new QueryWrapper<>();
            wrapper.eq("user_name",username).eq("password" ,password);
            UserTb one = iUserTbService.getOne(wrapper);
            if (null!=one){
                session.setAttribute("userName",one.getNickname());
                session.setAttribute("userId",one.getUserId());
                session.setAttribute("userImg",one.getUserImgUrl());
                session.setAttribute("username",one.getUserName());
            }
            //获取正在访问的用户
            Subject subject = SecurityUtils.getSubject();
            //如果当前用户验证过
            System.out.println(subject.isAuthenticated());
            //验证 关闭浏览器则需要重新验证
            // 记住我 就算关闭浏览器页同样是记住的
            //|| subject.isRemembered()
            if (subject.isAuthenticated()||subject.isRemembered()) {
                System.out.println("认证过的");
                return "index";
            }
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
            System.out.println("11111"+usernamePasswordToken);
            //记住我
            // usernamePasswordToken.setRememberMe(isok);
            try {
                subject.login(usernamePasswordToken);
            } catch (IncorrectCredentialsException in) {
                System.out.println("用户你密码不存在");
                request.setAttribute("failed","登录失败！密码不存在！");
                return "login";
            } catch (UnknownAccountException u) {
                request.setAttribute("failed","登录失败！用户名不存在！");
                System.out.println("用户不存在");
                return "login";
            } catch (AuthenticationException e) {
                System.out.println("该用户已经被禁用或未注册！");
                request.setAttribute("stop","你的账号被禁用或者没有注册！请联系客服！");
                return "login";
            }
            return "redirect:index";
        }
       return "login";
    }


    @RequestMapping("/myself")
    public  String mySelf(HttpServletRequest request){
       HttpSession session=request.getSession();
        String  userName = (String)session.getAttribute("username");
        System.out.println(userName);
        //用reqest从后拿 输入框的数据

        String password = request.getParameter("oldpassword");
        String nowpasswrd = request.getParameter("nowpassword");
        String twopassword = request.getParameter("twopassword");
        System.out.println(password+"-----"+nowpasswrd+"-----"+twopassword);
//        QueryWrapper wrapper=new QueryWrapper();
//        wrapper.eq("password",nowpasswrd);
        if("" != password & "" !=nowpasswrd & "" != twopassword & null!= password& null !=nowpasswrd & null != twopassword){
           if (nowpasswrd.equals(twopassword)){
               //重新查一次看看密码和用户名是否对应
               List<UserTb> userList = iUserTbService.getUserList(userName);
               String userName1=null;
               String password1=null;
               for (UserTb userTb : userList) {
                   userName1 = userTb.getUserName();
                   password1 = userTb.getPassword();
               }
               if(password.equals(password1)){
                   //数据库中有这个字段
                   if (null != userName1){
                       if(nowpasswrd.equals(twopassword)){
                           boolean b = iUserTbService.updatePassword(twopassword, userName);
                           if (b){
                               System.out.println("修改成功！");
                               request.setAttribute("success","修改成功！");
                               return "login";
                           }else {
                               System.out.println("修改失败！");
                               return "options";
                           }
                       }
                   }else{
                       return "options";
                   }
               }else{
                   request.setAttribute("nosuccess","输入的原密码错误!");
                   return "options";
               }
           }else {
               request.setAttribute("mustok","两次密码输入不一致！重新填写！");
               System.out.println("修改失败！");
               return "options";
           }
        }else {
            request.setAttribute("mustbe","不能有空！都必填！");
            System.out.println("没有操作！");
        }
        return "options";
    }


    @RequestMapping("/goout")
    public String goOut(HttpServletRequest request){
        try{
            HttpSession session=request.getSession();
            //销毁sessiondi
            session.invalidate();
        }catch (Exception e){
            return "redirect:/tologin";
        }
        return "redirect:/tologin";
    }

}

